package org.tis.tools.senior.module.core.web.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.tis.tools.model.common.ResultVO;
import org.tis.tools.senior.module.core.web.controller.request.LoginRequest;
import org.tis.tools.senior.module.developer.entity.SSvnAccount;

import javax.servlet.http.HttpServletRequest;

/**
 * describe: shiro认证相关端点
 *
 * @author zhaoch
 * @date 2018/9/16
 **/
@Slf4j
@RestController
@Api(value = "shiroController", tags = {"认证相关服务接口"})
public class ShiroController {

    /**
     * 登录方法
     * @param userInfo
     * @return
     */
    @PostMapping("/login")
    public ResultVO ajaxLogin(@RequestBody @Validated LoginRequest userInfo) {
        Subject subject = SecurityUtils.getSubject();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        log.info("userId:" + userInfo.getUserId() + " ip:" + request.getRemoteAddr()  + " 尝试登录");
        UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserId(), userInfo.getPassword());
        subject.login(token);
        JSONObject jsonObject = new JSONObject();
        SSvnAccount principal = (SSvnAccount) SecurityUtils.getSubject().getPrincipal();
        principal.setSvnPwd(null);
        jsonObject.put("userInfo", principal);
        jsonObject.put("token", subject.getSession().getId());
        log.info("userId:" + userInfo.getUserId() + " ip:" + request.getRemoteAddr() + " 登录成功");
        return ResultVO.success("登陆成功!", jsonObject);
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public ResultVO logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultVO.success("退出登录成功！");
    }

    /**
     * 未登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
     * @return
     */
    @RequestMapping(value = "/unauth")
    public ResultVO unauth() {
        throw new UnauthenticatedException();
    }

    @ApiOperation(value = "获取当前用户信息", notes = "无参数")
    @GetMapping("/user")
    public ResultVO info() {
        JSONObject jsonObject = new JSONObject();
        SSvnAccount principal = (SSvnAccount) SecurityUtils.getSubject().getPrincipal();
        principal.setSvnPwd(null);
        jsonObject.put("userInfo", principal);
        return ResultVO.success("查询成功！", jsonObject);
    }
}
